"""Add GatewayComputeModel.app_updated_at

Revision ID: e3b7db07727f
Revises: c83d45f9a971
Create Date: 2024-09-17 12:23:34.808431

"""

import uuid
from datetime import timedelta

import sqlalchemy as sa
import sqlalchemy_utils
from alembic import op

import dstack._internal.server.models
from dstack._internal.utils.common import get_current_datetime

# revision identifiers, used by Alembic.
revision = "e3b7db07727f"
down_revision = "c83d45f9a971"
branch_labels = None
depends_on = None


gateway_computes_table = sa.Table(
    "gateway_computes",
    sa.MetaData(),
    # partial description - only columns affected by this migration
    sa.Column("id", sqlalchemy_utils.UUIDType(binary=False), primary_key=True, default=uuid.uuid4),
    sa.Column("app_updated_at", dstack._internal.server.models.NaiveDateTime()),
)


def upgrade() -> None:
    # ### commands auto generated by Alembic - please adjust! ###
    with op.batch_alter_table("gateway_computes", schema=None) as batch_op:
        batch_op.add_column(
            sa.Column(
                "app_updated_at", dstack._internal.server.models.NaiveDateTime(), nullable=True
            )
        )

    # Should be in the past to trigger gateway update after migrations
    default_app_updated_at = get_current_datetime() - timedelta(minutes=60)
    op.get_bind().execute(
        (gateway_computes_table.update().values(app_updated_at=default_app_updated_at))
    )

    with op.batch_alter_table("gateway_computes", schema=None) as batch_op:
        batch_op.alter_column("app_updated_at", nullable=False)

    # ### end Alembic commands ###


def downgrade() -> None:
    # ### commands auto generated by Alembic - please adjust! ###
    with op.batch_alter_table("gateway_computes", schema=None) as batch_op:
        batch_op.drop_column("app_updated_at")

    # ### end Alembic commands ###
